package com.zf.yichat.config.quartz.job;

import com.alibaba.fastjson.JSON;
import com.zf.yichat.config.quartz.job.api.Message;
import com.zf.yichat.config.websocket.client.Client;
import com.zf.yichat.dto.UserDeviceDto;
import com.zf.yichat.dto.UserIpDto;
import com.zf.yichat.mapper.UserDeviceMapper;
import com.zf.yichat.mapper.UserIpMapper;
import lombok.extern.slf4j.Slf4j;
import org.quartz.JobExecutionContext;
import org.quartz.JobExecutionException;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.scheduling.quartz.QuartzJobBean;
import org.springframework.stereotype.Component;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@Component
@Slf4j
public class MyTestJob extends QuartzJobBean {


    @Autowired
    private UserIpMapper userIpMapper;

    @Autowired
    private UserDeviceMapper userDeviceMapper;

    @Override
    protected void executeInternal(JobExecutionContext jobExecutionContext) throws JobExecutionException {

        Map<String, List<Message>> joinedMsg = new HashMap<String, List<Message>>();
        List<Message> messages = new ArrayList<Message>();


        // 查询一个IP登录多个账号
        List<UserIpDto> userIpDtoList = userIpMapper.queryAllIPLoginMultipleAccounts();
        if (userIpDtoList.size() > 0) {
            userIpDtoList.forEach(ipDto -> {
                String ip = ipDto.getIp();
                String userNames = ipDto.getUserNames();
                Message msg = new Message();
                msg.setCode("ipMessage");
                msg.setMsg("登录IP: 【" + ip + "】，登录用户: {" + userNames + "}");
                messages.add(msg);
            });
        }

        // 查询一个设备地址登录多个账号
        List<UserDeviceDto> deviceDtoList = userDeviceMapper.queryAllDevLoginMultipleAccounts();
        if (deviceDtoList.size() > 0) {
            deviceDtoList.forEach(deviceDto -> {
                String device = deviceDto.getDevice();
                String userNames = deviceDto.getUserNames();
                Message msg = new Message();
                msg.setCode("devMessage");
                msg.setMsg("登录  设备: 【" + device + "】，登录用户: {" + userNames + "}");
                messages.add(msg);
            });
        }
        joinedMsg.put("messages", messages);
        try {
            Client client = Client.getInstance();
            log.info("client:" + client.hashCode());

            while(true) {
                Thread.sleep(1000);
                if(client.isOpen()) {
                    client.send(JSON.toJSONString(joinedMsg));
                    break;
                }
            }
        } catch (Exception e) {
            log.error("推送通知失败：", e);
        }

    }
}
